<?php 

    /**
     * creates package, accepts three parameters:
     * 
     * 1) the name of the package (example Intelligencer-0.8.1)
     * 2) destination, where to save
     * 3) where the current package is located
     *
     * Example of usage: 
     *  php create_package.php Intelligencer-1.1.1 "C:\my\projects\intelligencer" ..\..\
     */

    /**
     * require Intelligencer Loader
     */
    require_once dirname(__FILE__).'/../Intelligencer/itLoader.php';

    //if ($argc != 4) {
    //    die("Error: three incomings parameters are required");
    //}
    
    (isset($argv[1])) ? $name = $argv[1] : $name = 'Intelligencer-2.1.1';
    (isset($argv[2])) ? $dest = $argv[2] : $dest = 'C:/my/projects/intelligencer';
    (isset($argv[3])) ? $loc = $argv[3] : $loc = '../';
    
    if (!is_file("$loc/package.xml")) {
        die("Error: location is invalid: it does not contain package.xml");
    }
    
    if (!is_dir($dest) || !is_writable($dest)) {
        die("Error: destination does not exist or is not writable");
    }
    
    if (is_dir("$dest/$name")) {
        itUtil::deleteDir("$dest/$name");
    }
    
    if (!is_dir("$dest/$name")) {
        mkdir("$dest/$name");
    }
    copy("$loc/package.xml", "$dest/package.xml");
    recurse_copy($loc, "$dest/$name");
    
    exec("7za a $dest/$name.tar $dest/$name $dest/package.xml");
    exec("7za a $dest/$name.tar.gz $dest/$name.tar");
    
    unlink("$dest/$name.tar");
    unlink("$dest/package.xml");
    itUtil::deleteDir("$dest/$name");

    function recurse_copy($src, $dest) {
        $dir = opendir($src);
        @mkdir($dest);
        while(false !== ($file = readdir($dir))) {
            if (!in_array($file, array('.', '..', '.svn', 'package.xml', '.settings', '.project', '.buildpath', 'Doc', 'Scripts'))) {
                
                if (is_dir($src . '/' . $file)) {
                    recurse_copy($src . '/' . $file, $dest . '/' . $file);
                } 
                else {
                    copy($src.'/'.$file, $dest.'/'.$file);
                }
            }
        }
        closedir($dir);
    }
    
?>
